package com.scpii.api.util;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;

public class ImageUtil {
	public static byte[] resizeImage(BufferedImage inImage, int maxDim) {
		try {
			ImageIcon inImageIcon = new ImageIcon(inImage);
			int imh = inImageIcon.getIconHeight();
			int imw = inImageIcon.getIconWidth();
			double scale;
			if (imh <= maxDim && imw <= maxDim)
				scale = 1;
			else if (imh > imw)
				scale = (double) maxDim / (double) imh;
			else
				scale = (double) maxDim / (double) imw;

			int scaledW = (int) (scale * imw);
			int scaledH = (int) (scale * imh);

			BufferedImage tag = new BufferedImage(scaledW, scaledH,
					BufferedImage.SCALE_SMOOTH);
			Graphics g = tag.getGraphics();
			g.drawImage(inImage.getScaledInstance(scaledW, scaledH,
					Image.SCALE_SMOOTH), 0, 0, null);
			g.dispose();
			ByteArrayOutputStream outStream = new ByteArrayOutputStream();
			ImageIO.write(tag, "JPEG", outStream);
			return outStream.toByteArray();

		} catch (Exception ex) {
			ex.printStackTrace();
			return null;
		}
	}

	public static byte[] resizeImage(File in, int maxDim) {
		try {

			BufferedImage inImage = ImageIO.read(in);
			return resizeImage(inImage, maxDim);
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}

	public static byte[] resizeImage(byte[] in, int maxDim) {
		try {

			BufferedImage inImage = ImageIO.read(new ByteArrayInputStream(in));
			return resizeImage(inImage, maxDim);
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}
}
